package com.wlz.basic;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author wlz
 * @date 2022-07-03  3:04 下午
 */
@Slf4j
@Component
public class SpringProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void sendMessage(String tpoic, String msg) {
        this.rocketMQTemplate.convertAndSend(tpoic,msg);
    }

    public void sendMessageInTransaction(String topic, String msg) throws Exception{
        String[] tags = new String[] {"TagA", "TagB", "TagC", "TagD", "TagE"};

        for (int i = 0; i < 10; i++) {
            Message<String> message = MessageBuilder.withPayload(msg)
                    .setHeader(RocketMQHeaders.TRANSACTION_ID, "traansId" + i)
                    .setHeader(RocketMQHeaders.TAGS, tags[i % tags.length])
                    .setHeader("MyProp", "MyPorp_" + i)
                    .build();
            String destination = topic + ":" + tags[i % tags.length];

            TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(destination, message, destination);
            log.info("sendMessageInTransaction  transactionSendResult: {} ", transactionSendResult);

            Thread.sleep(10);
        }

    }


}
